package com.olah.email;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class Sender {

    private static final String CYING = "cyingk@qq.com";
    private static final String PASSWD = "snmsemmhpigfdcec";

    public static boolean sendMessage(String content, String single) {
        Properties properties = Config.getProperties();
        Session session = Session.getDefaultInstance(properties);
        session.setDebug(true);
        Message message = createMimeMessage(session, single, "Olah!!!验证码", content);
        return sender(session, message);
    }

    private static Message createMimeMessage(Session session, String email, String title, String content) {
        Message message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(CYING));
            message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(email));
            message.setSubject(title);
            message.setText(content);
            message.setSentDate(new Date());
            message.saveChanges();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return message;
    }

    private static boolean sender(Session session, Message message) {
        Transport transport = null;
        try {
            transport = session.getTransport();
            transport.connect(CYING, PASSWD);
            transport.sendMessage(message, message.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                assert transport != null;
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

}
